package eventfax.core

import java.io.IOException
import java.nio._
import java.net._
import java.nio.channels.{SelectionKey,Selector,ServerSocketChannel,SocketChannel}
import java.nio.charset.{CharacterCodingException,Charset,CharsetDecoder}
import java.util.Iterator;
import java.util.Set;
import scala.collection.mutable.ArrayBuffer

class FaxData(var dataString: StringBuilder) {
  
  val charset: Charset = Charset.forName("ISO-8859-1")
  val decoder: CharsetDecoder = charset.newDecoder()
  val byteArray: ArrayBuffer[Byte] = new ArrayBuffer[Byte]()
  def this() = this(new StringBuilder)

  //var dataString: StringBuilder = new StringBuilder()


  // FIXME: decoding each buffer as it comes is bad for performance
  def append(buffer: ByteBuffer) {
    if(buffer.hasArray()) {
      var tmp_array = buffer.array().slice(buffer.position,buffer.limit)
      byteArray ++= tmp_array
    } else {
      var data: String = (decoder.decode(buffer)).toString()
      dataString.append(data)
    }
  }

  // decodes the data thats there in the Byte Array to a String and appends the data to the
  // String Builder class
  def decode() = {
    if(!byteArray.isEmpty) {
      var data: String = new String(byteArray.toArray,"ISO-8859-1")
      dataString.append(data)
      byteArray.clear()
    }
  }

  override def toString(): String = this.dataString.toString
  def length: Int = this.dataString.length

  // return a ByteBuffer representation of data, which can be easily written to socket
  def buffer(): ByteBuffer = {
    //println("String Buffer length " + length)
    var bytes: Array[Byte] = toString().getBytes("ISO-8859-1")
    // println("Byte Array length " + bytes.length)
    var byteBuffer: ByteBuffer = ByteBuffer.allocate(bytes.length)
    byteBuffer.put(bytes)
    return byteBuffer
  }

  def +(subString: String) {
    dataString.append(subString)
    return this
  }
  
  def clear(): Unit = { dataString = new StringBuilder(); byteArray.clear(); }
}
